<?php

namespace GoWithFood\Controller;

use Common\Controller\ApiController;
use Common\Model\ModelException;
use Ruben\Yxyun\Yxim;
use Util\ModelUtils;

class GoWithFoodController extends ApiController {

    protected $Model = NULL;
    protected $field = ['food_id', 'sex', 'who_show', 'position','poiname', 'start_time', 'hour', 'minute', 'type', 'is_ontime', 'user_id', 'create_time', 'mark', 'audit', 'delete_time', 'lat', 'lng', 'adcode', 'citycode', 'city', 'district', 'street'];
    protected $user_field = ['user_id', 'face', 'nickname', 'sex', 'token'];

    public function _initialize() {
        parent::_initialize();
        $this->Model = D(CONTROLLER_NAME);
    }

    /*
     * 发布租房
     */

    public function store() {
        $input = $this->request();
        $this->checkNull($input, ['who_show', 'sex', 'start_time', 'type','lat', 'lng','citycode', 'city', 'district', 'street']);

        try {
            $id = $this->Model->publish($this->user['id'], $input);
            $this->createdResponse(['msg' => '发布成功', 'id' => $id, "url" => "/mobile/food/add"]);
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    /*
     * 更新租房
     */

    public function edit() {
        $input = $this->request();
        $this->checkNull($input, ['id', 'who_show', 'sex', 'position', 'start_time', 'type']);

        try {
            $this->Model->publish($this->user['id'], $input);
            $this->createdResponse(['msg' => '更新成功', "url" => "/mobile/food/add"]);
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    /*
     * 删除需求
     * 
     */

    public function del() {
        $user = $this->user;
        $input = $this->request();
        $id = $input['id'];
        $this->Model->where(['food_id' => $id, 'user_id' => $user['id'], 'delete_time' => 0])->setField('delete_time', time());
        $this->createdResponse(['msg' => '删除成功', "url" => ""]);
    }

    /*
     * 关闭和开启我的信息
     * 
     */

    public function closed() {
        $user = $this->user;
        $input = $this->request();
        $id = $input['id'];
        $closed = $input['closed'];
        $this->Model->where(['food_id' => $id, 'user_id' => $user['id'], 'delete_time' => 0])->setField('closed', $closed);
        $msg = $input['closed'] ? "关闭成功" : "开启成功";
        $this->createdResponse(['msg' => $msg, "url" => ""]);
    }

    /*
     * 收藏/取消收藏
     * 
     */

    public function favorite() {
        $user = $this->user;
        $input = $this->request();
        if ($user['id'] == $input['user_id']) {
            $this->errorResponse('401', '不能收藏自己的哦');
        }
        $RentroomFavoriteM = D('GoWithFoodFavorite');
        $id = $input['id'];
        $del_id = $input['del_id'];
        $where['user_id'] = $user['id'];
        if ($del_id) {
            $RentroomFavoriteM->delete($del_id);
            $msg = "取消收藏成功";
            $this->createdResponse(['msg' => $msg, "url" => ""]);
        } else {
            $this->checkNull($input, ['id']);
            $id = $RentroomFavoriteM->add([
                'user_id' => $user['id'],
                'food_id' => $input['id'],
                'to_user_id' => $input['user_id'],
                'add_time' => time()
            ]);
            $msg = "添加收藏成功";
            $this->createdResponse(['msg' => $msg, 'favorite' => ['favorite_id' => $id, 'food_id' => $input['id']], "url" => ""]);
        }
    }

    /*
     * 
     * 我的历史需求
     */

    public function mytravel() {
        $user = $this->user;
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $where = $rentroom = $pagination = [];

        $where['user_id'] = $user['id'];
        $rentroomM = D('GoWithFood');
        $count = $rentroomM->scope('history')->where($where)->count();

        if (!$count) {
            $this->response($rentroom, $pagination);
        }
        $rentroom = $rentroomM
                ->scope('history')
                ->where($where)
                ->order('create_time desc')
                ->page($page, $perPage)
                ->select();
        $pagination = pagination($count, $perPage, $page);
        $this->response($rentroom, $pagination);
    }

    /*
     * 
     * 我的收藏
     */

    public function myfavorite() {
        $user = $this->user;
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $where = $rentroom = $pagination = [];

        $where['user_id'] = $user['id'];
        $rentroomM = D('GoWithFoodFavorite');
        $count = $rentroomM->where($where)->count();
        if ($count > 0) {
        $rentroom = $rentroomM
                ->where($where)
                ->order('add_time desc')
                ->page($page, $perPage)
                ->select();
            $rentroom = $this->getrelation3($rentroom);
        ModelUtils::belongsTo($rentroom, ['foreignKey' => 'to_user_id', 'relation' => 'Account/Users', 'fields' => $this->user_field, 'refKey' => 'user_id', 'name' => 'author']);
        ModelUtils::belongsTo($rentroom, ['foreignKey' => 'food_id', 'relation' => 'GoWithFood/GoWithFood', 'refKey' => 'food_id', 'fields' => $this->field, 'name' => 'travel']);
        foreach ($rentroom as $key => &$value) {
                if(empty($value['author'])){
                    array_splice($rentroom,$key,1);
                }
            }
        }
        
        $pagination = pagination($count, $perPage, $page);
        $this->response($rentroom, $pagination);
    }

    /*
     * 获取用户
     * 
     */

    public function search() {
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $uid = $this->user['id'];
        $where = $rentroom = $pagination = [];
        $where = $this->whoShow($input);
        if ($page == 1) {

            // 不修改前端前提下避免重复数据
            S('post_page_lock_' . $uid, time(), 60);
        } else {
            $lastest = S('post_page_lock_' . $uid);
            // 不能完全避免
            if ($lastest)
                $where['create_time'] = ['elt', $lastest];
        }
        if (!empty($input['sex'])) {
            $input['sex'] = $input['sex']==1?2:1;
            $where['sex'] = ['neq',$input['sex']];
        }
        
        if (!empty($input['start_time'])) {
            $start_time = $input['start_time'];
            $day = date("Y-m-d", $start_time);
            $time = $day . ' ' . intval($input['hour']) . ':' . intval($input['minute']);
//            $etime = strtotime($time.'+30minute');
//            $stime = strtotime($time.'-30minute');
//            $start_time = strtotime($time);
            $where['start_time'] = ['egt', strtotime($time)];
//            $where['start_time'] = [['gt',$stime], ['lt',$etime]];
        }
//        if (!empty($input['end_time'])) {
//            $end_time = strtotime("+1 day", strtotime($input['end_time']));
//            $where['end_time'] = ['lt', $end_time];
//        }
//        $keyword = $input['position'];
//        if (!empty($keyword)) {
//            $where['position'] = ['like', "%{$keyword}%"];
//        }
        $poiname = $input['poiname'];
        if (!empty($poiname)) {
            $where['poiname'] = ['like', "%{$poiname}%"];
        }
        $type = $input['type'];
        if (!empty($type)) {
            $where['type'] = ['like', "%{$type}%"];
        }
        $where['citycode'] = $input['citycode'];
//        $where['adcode'] = $input['adcode'];
        $district = $input['district'];
        if (!empty($district)) {
            $where['district|position'] = ['like', "%{$district}%"];
        }
        
        $street = $input['street'];
        if (!empty($district)) {
            $where['street'] = ['like', "%{$street}%"];
        }        
//        $where['street'] = $input['street'];        
        $where = array_filter($where);

        $order = [];
        $order['create_time'] = 'desc';

        $count = $this->Model->scope('valid')->where($where)->count();
        if ($count>0) {
            $rentroom = $this->Model
                    ->scope('valid')
//                ->cache('food','60')
                    ->where($where)
                    ->field($this->field)
                    ->order($order)
                    ->page($page, $perPage)
                    ->select();
            ModelUtils::belongsTo($rentroom, ['foreignKey' => 'user_id', 'relation' => 'Account/Users', 'refKey' => 'user_id', 'fields' => $this->user_field, 'name' => 'author']);
            ModelUtils::belongsTo($rentroom, ['foreignKey' => 'food_id', 'relation' => 'GoWithFood/GoWithFoodFavorite', 'refKey' => 'food_id', 'where' => ['user_id' => $uid], 'name' => 'favorite']);
            $rentroom = $this->getrelation($rentroom);
            foreach ($rentroom as $key => &$value) {
                if(empty($value['author'])){
                    array_splice($rentroom,$key,1);
                }
            }
        }
        $pagination = pagination($count, $perPage, $page);
        $this->response($rentroom, $pagination);
    }

}
